<script setup>
import OApageheader from '../../components/OApageheader.vue';
import {ref,reactive,onMounted,computed,watch} from 'vue';
import {ElMessage} from 'element-plus';
import apiClient from '../../api/api';
import OAPagination from '../../components/OAPagination.vue';
import OAdialog from '../../components/OAdialog.vue';


let dialogFormVisible = ref(false); // 控制对话框的显示与隐藏
let formLabelWidth = '100px'; // 表单标签的宽度
let form = reactive({ // 表单数据
    title: '',
    absent_type_id: null,
    date_range: [], // 日期范围
    content: ''

});
let absent_types = ref([]); // 假条类型数据

let responder = reactive({ // 审批人数据
    realname: '', // 审批人姓名
    email: '' // 审批人邮箱 
});

let responder_str = computed(() => { // 计算属性，返回审批人姓名和邮箱
  if(responder.email){
    // 返回审批人姓名
    return responder.realname;   
    }else{
      return "无"
}
})


let absentform = ref(); // 表单实例

let absents = ref([]); // 个人考勤数据

let pagination = reactive({ // 分页数据
  total: 0, // 总条数
  page: 1, // 当前页码
  pageSize: 5, // 每页显示条数

});

const pageabsents = async (page) => {
  try {
    const res_absent = await apiClient.get('absent/absents/', {
      params: {
        page: page,
        page_size: pagination.pageSize,
      }
    });

    let total = res_absent.data.count; // 获取总条数
    pagination.total = total; // 将总条数赋值给 pagination.total
    let results = res_absent.data.results; // 获取分页数据列表
    absents.value = results; 
  } catch (error) {
    ElMessage.error(error.message);
  }
};


watch(() => pagination.page, (newVal) => { // 监听分页数据变化
      pageabsents(newVal); // 重新获取分页数据
  });

let rules = reactive({ // 表单验证规则
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    absent_type_id: [
        { required: true, message: '请选择假条类型', trigger: 'change' },
    ],
    date_range: [ // 日期范围验证规则
        { required: true, message: '请选择日期范围', trigger: 'blur' }, 
    ],
    content: [ // 内容验证规则
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
});
const onShow = () => {
    form.absent_type_id = null; // 重置表单数据
    form.date_range = []; // 重置日期范围
    form.title = ''; // 重置标题
    form.content = ''; // 重置内容
    dialogFormVisible.value = true; // 打开对话框
}

const onSubmit = () => { // 提交表单
  absentform.value.validate(async (valid, fields) => { // 验证表单
    if (valid) { // 如果验证通过
      try { 
        let res = await apiClient.post('absent/absents/', {  // 添加表单数据
          title: form.title,
          type_id: form.absent_type_id,
          start_time: form.date_range[0], // 开始日期
          end_time: form.date_range[1], // 结束日期
          content: form.content,
        }); 
        console.log(res); 
        ElMessage.success('提交成功'); 
        dialogFormVisible.value = false; // 关闭对话框
        pageabsents(pagination.page); // 提交成功后重新获取分页数据

      } catch (detail) { 
        ElMessage.error(detail); 
      }
    } else { // 如果验证不通过，提示错误信息
      ElMessage.error('请输入正确的信息');
    }
  });
}

// 页面加载完成后执行
onMounted(async() => { 
  try { 
    // 尝试获取假条类型数据
    let typeres = await apiClient.get('absent/absenttypes/'); // 获取假条类型数据
    absent_types.value = typeres.data; // 将假条类型数据赋值给 absent_types
  //  获取审批人数据
    let res_responder = await apiClient.get('absent/responder/'); // 获取审批人数据
    responder.realname = res_responder.data.realname; 
    responder.email = res_responder.data.email; 
// 获取个人考勤数据
    pageabsents(1); // 调用分页函数，初始化获取第1页的数据


  } catch (error) { // 如果获取数据失败，打印错误信息
    ElMessage.error(error.message); // 提示错误信息
  }

})

   
</script>

<template>
  <el-space direction="vertical" fill :size="20" style="width: 100%">
      <OApageheader content="个人考勤"></OApageheader>
      <!-- card卡片 -->
      <el-card style="text-align: right;">
        <el-button type="primary" @click="onShow"><el-icon><Plus /></el-icon>发起考勤</el-button>
      </el-card>

      <!-- 表格 -->
        <el-card>
            <!-- data必须是一个数组，prop表数组的对象，label是列标题（表头） -->
          <el-table :data="absents" style="width: 100%">   
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="requester.realname" label="申请人" />
              <el-table-column prop="type.name" label="请假类型" />
              <el-table-column prop="content" label="原因" />
              <el-table-column prop="creat_time" label="发起时间" />

              <el-table-column prop="start_time" label="开始日期" />
              <el-table-column prop="end_time" label="结束日期" />
              <el-table-column  label="审核领导">
                  {{ responder_str }}
              </el-table-column>
              
              <el-table-column prop="reply_content" label="反馈意见" />
              <el-table-column prop="status" label="审核状态" >
                  <template #default="scope">
                      <el-tag type="info" v-if="scope.row.status==1"> 审核中</el-tag>
                      <el-tag type="success" v-else-if="scope.row.status==2"> 审核通过</el-tag>
                      <el-tag type="danger" v-else> 拒绝</el-tag>
                  </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <template #footer>
              <!-- <el-pagination background layout="prev, pager, next" :total="pagination.total" v-model:current-page="pagination.page" :page-size="pagination.pageSize" /> -->
              <!-- 分页组件封装： -->
              <OAPagination :total="pagination.total" v-model="pagination.page" :page-size="pagination.pageSize" />
            </template>
        </el-card>
  </el-space>
  <!-- 对话框 -->
  <!-- 对话框组件封装： -->
   <OAdialog title="发起请假" v-model="dialogFormVisible" @submit="onSubmit">
      <el-form :model="form" :rules="rules" ref="absentform" >
        <el-form-item label=" 标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="请假类型" :label-width="formLabelWidth" prop="absent_type_id">
          <el-select v-model="form.absent_type_id" placeholder="请选择请假类型">
            <el-option v-for="item in absent_types" :label="item.name" :value="item.id" :key="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="请假时间" :label-width="formLabelWidth" prop="date_range">
          <el-date-picker
          v-model="form.date_range"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="介绍日期"
        />
        </el-form-item>
        <el-form-item label="审批领导" :label-width="formLabelWidth">
          <el-input :value="responder_str" readonly disabled autocomplete="off" />
        </el-form-item>
        <el-form-item label="请假理由" :label-width="formLabelWidth" prop="content">
          <el-input
          type="textarea"
          v-model="form.content"
          autocomplete="off" 
          />
        </el-form-item>
      </el-form>
   </OAdialog>


</template>

<style scoped>
.el-pagination {
  justify-content: center;
}
.el-space  :deep(.el-space__item){
  width: 100%;
}
</style>
